//***************************************************************************************************************
//Author: Alfredo Scoppa 
//file: index.js
//***************************************************************************************************************
$(function() {
	var subjectNumber;
	var subjectName;
	
	var fiubaPath = new String("http://intra.fi.uba.ar/insc/consultas/");
	var local = new String(window.location);
	var codigos = new Array();
	
	local = local.substr(0,local.length-11);
	
	$.ajax(
	{
		type: "GET",
		url: "php/initIndex2.php",
		dataType: 'html',
		success: function(datos)
		{
		  alert(datos);
		  $('#departments').html(datos);
		},
		error: function(obj1, e, obj2)
		{
			alert("Se produjo un error : "+ e);
		}
	});
	
	$("#departments").change(function(){
			subjectNumber = $("#departments").val();
			subjectName = new String($("#departments :selected").text());
			
			if (subjectName.indexOf(" ")>0)
				subjectName = "";
				
			$("#materias").load("http://intra.fi.uba.ar/insc/consultas/consulta_materias.jsp?departamento="+subjectNumber+"&descdepartamento="+subjectName+" .tablaitem a",
					function () {
						$("#materias a").each(function(item){
													var link = $(this).attr("href");
													codigos.push(link.replace(local,fiubaPath));
													$(this).attr("href",codigos[item]);									
												}).filter(":even").each(function(item){
													$(this).before(" <br><br>");
												});
					});	
			
	});
	
	$("#subjectInfo").click(function(){
		var subject = $("#subject").val();
		alert("SubjectName: "+getSubjectName(subject)+" | SubjectNumber: "+ getSubjectNumber(subject) + " | DepartmentNumber: " + getDepartmentNumber(subject));
	});
	
	$("#subjectsCount").click(function(){
		alert(getSubjectsCount());
	});
		
});

function getSubjectsCount(){
	var count = $("#materias a:even").size();
	return count;
}

function getSubjectName(subjectPosition){	
	var subjectText = new String($("#materias a:odd").slice(subjectPosition-1,subjectPosition).text());
	return subjectText;
}

function getSubjectNumber(subjectPosition){	
	var subjectText = new String($("#materias a:even").slice(subjectPosition-1,subjectPosition).text());
	return subjectText.substr(0,4);
}

function getDepartmentNumber(subjectPosition){
	return getSubjectNumber(subjectPosition).substr(0,2);
}
